#! /usr/bin/env node

// shell操作
const shell = require('shelljs')
// 下载github模板
const download = require('download-git-repo')
// loading
const ora = require('ora')
const chalk = require('chalk')
const clear = require('clear')
const common = require('../../common/index')

const getTemplateUrl = (templateName) => {
  let url = ''
  switch (templateName) {
    case common.INIT_TEMPLATE['client-view'].value:
      url = 'direct:https://gitlab.wisetimes.cn/xuyd/client-template/-/archive/master/client-template-master.zip'
      break
    case common.INIT_TEMPLATE['client-usercenter'].value:
      url = 'direct:https://gitlab.wisetimes.cn/xuyd/cli-usercenter-template/-/archive/master/cli-usercenter-template-master.zip'
      break
    default:
      break
  }

  if (!url) {
    console.log('')
    console.log(`${chalk.red(`❗ 没有找到${templateName}对应的模板地址，请联系开发者补充`)}`)
    process.exit(1)
  }

  return url
}

const checkSelectTemplate = (templateName, dirname) => {
  const needDirArr = [common.INIT_TEMPLATE.cms.value]
  if (needDirArr.includes(templateName) && !dirname) {
    console.log('')
    console.log(`${chalk.red(`❗ 模板（${common.INIT_TEMPLATE[templateName].label}）需要设置项目名称`)}`)
    console.log(`${chalk.red(`❗ 执行 xz-cli init xxx 设置项目名称`)}`)
    process.exit(1)
  }
}
const templateSpinner = ora(chalk.yellow('🕒 正在下载模板,请稍等...'))
const installSpinner = ora(chalk.yellow('🕒 正在安装项目依赖,请稍等...'))
const initProcess = (answers, dirname) => {
  const { templateName, userName, userEmail, description, downloadMethod } = answers

  checkSelectTemplate(templateName, dirname)

  if (templateName === common.INIT_TEMPLATE.cms.value) {
    downloadCmsTemplate(dirname)
    return
  }

  const _dirname = dirname
  const _path = process.cwd()
  const _projectPath = _dirname ? `${_path}/${_dirname}` : _path


  templateSpinner.start()
  // 创建相关的文件
  shell.cd(_path)
  if (_dirname) {
    shell.rm('-rf', _projectPath)
    shell.mkdir(_dirname)
  }

  const template = getTemplateUrl(templateName)
  download(
    template,
    _projectPath,
    (err) => {
      templateSpinner.stop()
      console.log('')
      console.log(`${chalk.green('🧡💛 模板下载完成💛🧡')}`)
      console.log('')

      if (err) {
        clear()
        console.error(`${chalk.yellow('❌下载模板失败 : ')}${chalk.red(err.message.trim())}`)
        process.exit(1)
      } else {
        // 替换package.json内容
        const replacePkg = `${_projectPath}/package.json`
        if (shell.test('-e', replacePkg)) {
          if (_dirname) {
            shell.sed('-i', '{{name}}', _dirname, replacePkg)
          }
          shell.sed('-i', '{{author}}', `${userName} <${userEmail}>`, replacePkg)
          shell.sed('-i', '{{description}}', description, replacePkg)
        } else {
          console.log('')
          console.log(`${chalk.red('❗ 项目可能缺少package.json文件，无法替换作者、邮箱和描述等信息 ')}`)
        }

        const downloadStr = downloadMethod === 'npm' ? 'npm install' : 'yarn'

        const runStr = downloadMethod === 'npm' ? 'npm run dev' : 'yarn dev'

        // 下载成功, 安装相关依赖
        installSpinner.start()

        const execStr = _dirname ? `cd ${_dirname} && ${downloadStr}` : downloadStr
        shell.exec(execStr, { fatal: true }, (err) => {
          if (err !== 0) {
            console.log('')
            console.log(`${chalk.red(`❗ 依赖安装出错，请查看上方错误后，手动执行${downloadStr}`)}`)
          }

          installSpinner.stop()
          console.log(`
${chalk.green('💙💜 依赖下载完成💜💙')}

${chalk.green('💗💗 模版已生成，按照以下提示操作💗💗')}
          `)

          if (_dirname) {
            console.log(`
${chalk.blue(`👉 cd ${_dirname}`)}

${chalk.blue(`👉 ${runStr}`)}
            `)
          } else {
            console.log(`${chalk.blue(`👉 ${runStr}`)}`)
          }
        })
      }
    }
  )
}

const downloadCmsTemplate = (dirname) => {
  const _dirname = dirname
  const _path = process.cwd()

  const getTemplateUrl = (type = '') => {
    if (type === 'static') {
      return 'direct:https://gitlab.wisetimes.cn/xuyd/cli-phpcms-template/-/archive/static/cli-phpcms-template-static.zip'
    }

    return 'direct:https://gitlab.wisetimes.cn/xuyd/cli-phpcms-template/-/archive/master/cli-phpcms-template-master.zip'
  }

  const downloadContentTemplate = () => {
    // 下载到 phpcms/templates
    const contentPath = `${_path}/phpcms/templates`
    const contentProjectPath = `${contentPath}/${_dirname}`
    const contentTemplatePath = `${contentProjectPath}/content`

    templateSpinner.start()

    // 创建相关的文件
    shell.cd(contentPath)
    if (_dirname) {
      shell.rm('-rf', contentProjectPath)
      shell.mkdir(_dirname)
      shell.mkdir(contentTemplatePath)
    }

    const contentTemplate = getTemplateUrl()
    download(
      contentTemplate,
      contentTemplatePath,
      (err) => {
        if (err) {
          clear()
          console.error(`${chalk.yellow('❌下载模板失败 : ')}${chalk.red(err.message.trim())}`)
          process.exit(1)
        }

        templateSpinner.stop()
        console.log(`${chalk.green('🧡💛 content 模板下载完成💛🧡')}`)

        const files = shell.ls(contentTemplatePath)
        const fileNames = files.filter(file => {
          return shell.test('-f', `${contentTemplatePath}/${file}`)
        })
        fileNames.forEach(filename => {
          const replaceFile = `${contentTemplatePath}/${filename}`
          shell.sed('-i', '{{name}}', _dirname, replaceFile)
        })
      }
    )
  }

  const downloadStaticTemplate = () => {
    // 下载到static
    const staticPath = `${_path}/statics`
    const staticProjectPath = `${staticPath}/${_dirname}`

    templateSpinner.start()
    // 创建相关的文件
    shell.cd(staticPath)
    if (_dirname) {
      shell.rm('-rf', staticProjectPath)
      shell.mkdir(_dirname)
    }

    const staticTemplate = getTemplateUrl('static')
    download(
      staticTemplate,
      staticProjectPath,
      (err) => {
        if (err) {
          clear()
          console.error(`${chalk.yellow('❌下载模板失败 : ')}${chalk.red(err.message.trim())}`)
          process.exit(1)
        }

        templateSpinner.stop()
        console.log('')
        console.log(`${chalk.green('🧡💛 static 模板下载完成💛🧡')}`)
        console.log('')

        downloadContentTemplate()
      }
    )
  }

  downloadStaticTemplate()
}

module.exports = initProcess